/*
 * Copyright 2012 Focus Technology, Co., Ltd. All rights reserved.
 */
package com.coderonrails.cdistr.master.comint;

import java.net.ServerSocket;

/**
 * MasterServicesImpl.java
 * 
 * @author chenjianguo
 */
public class MasterServicesImpl implements MasterServices {
    private MasterConfig config;
    private ServerSocket manageServerSocket = null;
    private ServerSocket dataServerSocket = null;
    private ServerSocket heartServerSocket = null;
    private boolean isRunning = false;

    /*
     * (non-Javadoc)
     * @see com.coderonrails.cdistr.master.comint.MasterServices#setMasterConfig(com.coderonrails.cdistr.master.comint.
     * MasterConfig)
     */
    @Override
    public void setMasterConfig(MasterConfig config) {
        this.config = config;
    }

    /*
     * (non-Javadoc)
     * @see com.coderonrails.cdistr.master.comint.MasterServices#startService()
     */
    @Override
    public void startService() {
        try {
            manageServerSocket = new ServerSocket(config.getManagePort());
            dataServerSocket = new ServerSocket(config.getDataPort());
            heartServerSocket = new ServerSocket(config.getHeartPort());
            isRunning = true;
            //

            ManageServerThread ms = new ManageServerThread();
            ms.setMasterServer(this);
            ms.setServerSocket(manageServerSocket);
            Thread t_heart = new Thread(ms);
            t_heart.start();
            //
            HeartServerThread ht = new HeartServerThread();
            ht.setMasterServer(this);
            ht.setServerSocket(heartServerSocket);
            Thread t_manage = new Thread(ht);
            t_manage.start();
            //
            Thread t_mon = new Thread(new MonitorThread(this));
            t_mon.start();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * (non-Javadoc)
     * @see com.coderonrails.cdistr.master.comint.MasterServices#stopService()
     */
    @Override
    public void stopService() {
        setRunning(false);
    }

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }

    public static void main(String[] args) {
        MasterServices MS = new MasterServicesImpl();
        MS.setMasterConfig(new MasterConfig());
        MS.startService();
    }

}
